package userFileModuleApi

import (
	"KumquatDrivesServices/common/res"
	"KumquatDrivesServices/enums"
	"KumquatDrivesServices/global"
	"KumquatDrivesServices/model"
	"KumquatDrivesServices/utils"
	"errors"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"gorm.io/gorm"
)

type getDownLoadUrlRequest struct {
	FileIds []model.SnowflakeIdType `form:"fileIds" binding:"required"`
}

func (UserFileModuleApi) GetDownLoadCode(c *gin.Context) {
	var req getDownLoadUrlRequest
	if err := c.ShouldBindQuery(&req); err != nil {
		res.FailWithCode(res.PARAM_ERR, c)
		return
	}
	userId := utils.GetUserId(c)
	//查询文件信息
	var FileInfoList []model.FileModel
	if err := global.DB.Where("id in ? and user_id=? and del_flag=?", req.FileIds, userId, enums.Normal).Find(&FileInfoList).Error; err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			res.FailWithCode(res.PARAM_ERR, c)
			return
		}
		logrus.Errorf("GetDownLoadCode find file err:%v", err)
		res.FailWithCode(res.SYS_ERR, c)
		return
	}
	var downLoadIdList []string
	for _, fileInfo := range FileInfoList {
		str := utils.RandomString(enums.DownloadIdLen)
		downLoadId := enums.DirectDownloadId.GetDownloadId(str)
		downLoadIdList = append(downLoadIdList, str)
		var fileTree []*utils.FileTree
		if fileInfo.IsFolder == enums.Folder {
			Tree, err := utils.GetFileTree(userId, fileInfo)
			if err != nil {
				logrus.Errorf("GetDownLoadCode err:%v", err)
				res.FailWithCode(res.SYS_ERR, c)
				return
			}
			fileTree = append(fileTree, Tree...)
		} else {
			fileTree = append(fileTree, &utils.FileTree{
				FileId:   fileInfo.ID,
				FilePid:  fileInfo.FilePid,
				FileName: fileInfo.FileName,
				FilePath: fileInfo.FilePath,
				IsFolder: fileInfo.IsFolder,
				Children: []*utils.FileTree{},
			})
		}
		if err := utils.CacheDownloadIdOfFileInfo(downLoadId, fileTree); err != nil {
			logrus.Errorf("GetDownLoadCode err:%v", err)
			res.FailWithCode(res.SYS_ERR, c)
			return
		}
	}
	res.OkWithData(downLoadIdList, c)
}
